package top.pcat.handle;

import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import lombok.extern.slf4j.Slf4j;
import redis.clients.jedis.Jedis;
import top.pcat.config.ServerConfig;
import top.pcat.entity.Message;
import top.pcat.entity.Sender;
import top.pcat.service.*;
import top.pcat.util.RedisPoolUtil;

import java.io.IOException;
import java.text.SimpleDateFormat;

@Slf4j
public class NettyServerHandler extends SimpleChannelInboundHandler<Message> {

    private final SimpleDateFormat simpleDateFormat = new SimpleDateFormat("MM-dd HH:mm:ss");

    private MessagingService messagingService = new MessagingService();

    @Override
    public void channelRead0(ChannelHandlerContext ctx, Message msg) throws IOException {
        Channel channel = ctx.channel();
        log.info("收到用户消息 ----->  "+msg);
        msg.setServerId(ServerConfig.serverId);
        switch (msg.getController()){
            case 0:
                //普通消息
                messagingService.normalMessage(msg);
                break;
            case 1:
                // 向客户端发送的第一条消息
                messagingService.firstMessage(msg,channel);
                break;
            case 2:
                // 发送有人加入聊天室
                messagingService.newMemberMessage(msg,channel);
                break;
            case 3:
                //发送红包
                messagingService.redPacketMessage(msg, channel);
                break;
            case 4:
                //抢红包结果
                messagingService.redPacketResultMessage(msg, channel);
                break;
            case 5:
                //随机私聊消息
                messagingService.randomMessage(msg, channel);
                break;
            case 6:
                // 收到用户新建聊天室消息
                messagingService.newRoomMessage(msg, channel);
                break;

        }


    }

    /**
     * 建立连接以后第一个调用的方法
     */
    @Override
    public void handlerAdded(ChannelHandlerContext ctx) throws Exception {
        Channel channel = ctx.channel();
        log.info("handlerAdded 建立连接以后第一个调用的方法");
        ServerConfig.channelGroup.add(channel);
    }

    /**
     * 连接发生异常时触发
     */
    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause){
        Channel channel = ctx.channel();
        String senderName = ServerConfig.channelToSenderMap.get(channel).getSenderName();
        cause.printStackTrace();
        log.info("用户"+senderName+"失去同步:"+cause.getMessage()+"\n");
        ctx.close();
    }

    /**
     * 断开连接会触发该消息
     */
    @Override
    public void handlerRemoved(ChannelHandlerContext ctx)  {
        log.info("收到连接断开，移除用户信息");
        Channel channel = ctx.channel();
        Sender sender = ServerConfig.channelToSenderMap.get(channel);
        String senderId = sender.getSenderId();
        long roomId = sender.getRoomId();

        log.info(String.valueOf(sender));
        new ChatRoomService().removeUserFromChatroom(roomId,senderId);
        ServerConfig.senderToChannelMap.remove(senderId);
        String senderName = ServerConfig.channelToSenderMap.get(channel).getSenderName();
      
        Message message = new Message();
        message.setMesContent(" "+senderName+" 离开了 ");
        message.setSenderId(senderId);
        message.setSenderName(senderName);
        message.setController(1);
        message.setServerId(ServerConfig.serverId);
        message.setRoomId(roomId);
        messagingService.normalMessage(message);

        Jedis jedis = RedisPoolUtil.getJedis();
        jedis.srem("server:"+ServerConfig.serverHost+":online_users",senderId);
    }
}

